<?php

// * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// * Copyright 2014 The Herosphp Authors. All rights reserved.
// * Use of this source code is governed by a MIT-style license
// * that can be found in the LICENSE file.
// * +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

declare(strict_types=1);

namespace herosphp\plugin\storage;

use herosphp\core\Config;
use herosphp\exception\HeroException;
use herosphp\plugin\storage\core\Manager;
use herosphp\plugin\storage\core\Uploader;

/**
 * 文件存储管理工具
 * ---------------------------
 * @author RockYang<yangjian102621@gmail.com>
 */
class Storage
{
    protected static array $_config = [];

    public static function init(): void
    {
        $config = Config::get('storage');
        static::$_config = $config;
        // init the storage handler
        static::handler($config['default_handler']);
    }

    public static function handler(string $key): void
    {
        if (isset(static::$_config['handlers'][$key])) {
            $handler = static::$_config['handlers'][$key];
            if (!class_exists($handler['class'])) {
                throw new HeroException("storage handler class not found '{$handler['class']}'");
            }

            if (isset($handler['config'])) {
                static::$_config['handler'] = new $handler['class']($handler['config']);
            } else {
                static::$_config['handler'] = new $handler['class']();
            }
        }
    }

    public static function getUploader(): ?Uploader
    {
        return new Uploader(
            static::$_config['max_size'],
            static::$_config['allow_ext'],
            static::$_config['reject_ext'],
            static::$_config['handler']
        );
    }

    public static function getManager(): ?Manager
    {
        return null;
    }
}

Storage::init();
